package loginpage

import (
	"fmt"
	"html/template"
	"myOJ/login"
	"net/http"
	"time"

	"github.com/google/uuid"
)

func LoginPage(w http.ResponseWriter, r *http.Request) {
	t := template.Must(template.ParseFiles("view/loginpage/loginpage.html"))
	t.Execute(w, nil)
}

func genCookie(username string) *http.Cookie {
	var cook http.Cookie
	cook.Name = username
	cook.Value = uuid.New().String()
	expiration := time.Now()
	expiration = expiration.AddDate(1, 0, 0)
	cook.Expires = expiration
	return &cook

}

func Logining(w http.ResponseWriter, r *http.Request) {
	name := r.FormValue("username")
	password := r.FormValue("password")

	if login.Verify(name, password) {
		cook := genCookie(name)
		fmt.Println(cook)
		http.SetCookie(w, cook)
		http.Redirect(w, r, "/", 301)
	} else {
		http.Redirect(w, r, "/loginError", 301)
	}

}

func LoginError(w http.ResponseWriter, r *http.Request) {
	t := template.Must(template.ParseFiles("view/loginpage/loginError.html"))
	t.Execute(w, nil)
}
